package com.xudow.app.dynamicstate_old.module.user;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jude.beam.expansion.BeamBaseActivity;
import com.jude.tagview.TAGView;
import com.jude.utils.JUtils;
import com.squareup.picasso.Picasso;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.ImageModel;
import com.xudow.app.dynamicstate_old.data.RongYunModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.domain.Config;
import com.xudow.app.dynamicstate_old.domain.entity.UserIntroduce;
import com.xudow.app.dynamicstate_old.domain.entity.UserLabel;
import com.xudow.app.dynamicstate_old.domain.entity.WrapUserIntroduce;
import com.xudow.app.dynamicstate_old.widget.ProgressDialogTransform;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.util.StringUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class UserProfileActivity extends BeamBaseActivity {

    public static final String USER_PROFILE_ID = "user_profile_id";
    public static final String AGNCY_ID = "agency_id";
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.text_attention)
    TextView textAttention;
    @BindView(R.id.ll_attention)
    LinearLayout llAttention;
    @BindView(R.id.ll_message)
    LinearLayout llMessage;
    @BindView(R.id.view_link)
    LinearLayout viewLink;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.img_attention)
    ImageView imgAttention;
    private long mUserProfileId;

    @BindView(R.id.dynamic_activity_userprofile_cover)
    ImageView mCover;
    @BindView(R.id.dynamic_activity_userprofile_avatar)
    ImageView mAvatar;
    @BindView(R.id.dynamic_activity_userprofile_name)
    TextView mName;
    @BindView(R.id.dynamic_activity_userprofile_gender)
    ImageView mGender;
    @BindView(R.id.dynamic_activity_userprofile_following_num)
    TextView mFollowingNum;
    @BindView(R.id.dynamic_activity_userprofile_follower_num)
    TextView mFollowerNum;
    @BindView(R.id.dynamic_activity_userprofile_tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.dynamic_activity_userprofile_pager)
    ViewPager mViewPager;
    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.fl_info)
    FrameLayout frameLayoutUserInfo;
    @BindView(R.id.rl_info)
    RelativeLayout rlInfo;
    @BindView(R.id.ll_top_attention)
    View llTopAttention;
    @BindView(R.id.ll_top_fans)
    View llTopFans;
    @BindView(R.id.ll_tool)
    View llTool;
    @BindView(R.id.dynamic_activity_userprofile_labellayout)
    LinearLayout mTagContainer;
    @BindView(R.id.image_identify)
    ImageView identify;
    @BindView(R.id.text_sign)
    TextView textSign;
    @BindView(R.id.text_location)
    TextView textLocation;
    @BindView(R.id.ll_location)
    View llLocation;


    // 供三个Fragment共享, 未测试此方法有效性
    public UserIntroduce mUserIntroduce;
    private String data;
    PageAdapter pageAdapter;
    XApplication app;
    String[] titles = new String[]{"动态", "简介", "课程"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dynamic_activity_userprofile);
        ButterKnife.bind(this);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                final float size = -verticalOffset;
                final float total = appBarLayout.getTotalScrollRange();
                double per = 1.0f - (size / total);
                rlInfo.setAlpha((float) per);
            }
        });
        app = (XApplication) getApplication();

//        mUserIntroduce = new UserIntroduce();
//        mUserProfileId = getIntent().getLongExtra(USER_PROFILE_ID, -1);
        if (getIntent().hasExtra(AGNCY_ID)) {
            mUserProfileId = getIntent().getLongExtra(AGNCY_ID, -1);
            getAgencyInfo();
        } else {
            mUserProfileId = getIntent().getLongExtra(USER_PROFILE_ID, -1);
            getUserInfo();
        }
        loadUserIntroduce();
    }

    private void loadUserIntroduce() {
        if (app.getUserProfileId() == mUserProfileId) {
            llTool.setVisibility(View.GONE);
        }
    }

    private void getAgencyInfo() {
        DynamicModel.getInstance().getAgencyInfo(mUserProfileId)
                .compose(new ProgressDialogTransform<>(this, "加载中"))
                .subscribe(this::setUserInfo);
    }

    private void getUserInfo() {
        DynamicModel.getInstance().getUserIntroduce(mUserProfileId)
                .compose(new ProgressDialogTransform<>(this, "加载中"))
                .subscribe(this::setUserInfo);
    }

    private void setUserInfo(WrapUserIntroduce userIntroduce) {
        loadUserIntroduce();
        mUserIntroduce = userIntroduce.getMainData();
        data = userIntroduce.getData();
        if (TextUtils.isEmpty(mUserIntroduce.getHeadUrl())) {
            Picasso.with(UserProfileActivity.this).load(R.drawable.default_head_img).into(mAvatar);
        } else
            Picasso.with(UserProfileActivity.this).load(ImageModel.getXueDouImage(mUserIntroduce.getHeadUrl())).into(mAvatar);
        if (!TextUtils.isEmpty(mUserIntroduce.getCoverPhoto()) && mUserIntroduce.getCoverPhoto().startsWith("http"))
            Glide.with(this)
                    .load(ImageModel.getLargeImage(mUserIntroduce.getCoverPhoto()))
                    .error(R.mipmap.bg)
                    .into(mCover);
        collapsingToolbar.setTitle(mUserIntroduce.getUserName());
        mName.setText(mUserIntroduce.getUserName());
        mFollowingNum.setText(mUserIntroduce.getAttentionNum() + "");
        mFollowerNum.setText(mUserIntroduce.getFansNum() + "");
        if (mUserIntroduce.getGender() != 0)
            mGender.setImageResource(mUserIntroduce.getGender() == 1 ? R.drawable.dynamic_profile_man : R.drawable.dynamic_profile_woman);
        if (!StringUtils.isEmpty(mUserIntroduce.getCity())) {
            String address = mUserIntroduce.getCity();
            if (!StringUtils.isEmpty(mUserIntroduce.getArea()))
                address = address + "," + mUserIntroduce.getArea();
            textLocation.setText(address);
        } else
            llLocation.setVisibility(View.INVISIBLE);
        List<UserLabel> userLabels = mUserIntroduce.getLabelList();
        if (userLabels.size() != 0) {
            textSign.setText("签名：" + userLabels.get(0).getLabelName());
            if (userLabels.size() == 2) {
                mTagContainer.removeAllViews();
                TAGView tagView = new TAGView(this);
                tagView.setBackgroundColor(getResources().getColor(R.color.talent_tag_bg));
                tagView.setRadius(JUtils.dip2px(5));
                tagView.setTextColor(getResources().getColor(R.color.talent_tag_text));
                tagView.setTextColor(Color.YELLOW);
                tagView.setTextSize(13);
                tagView.setText(userLabels.get(1).getLabelName());
                mTagContainer.addView(tagView);
            }
        }

        if (mUserIntroduce.getUserProfileId() != app.getUserProfileId() && app.isLogin()) {
            getToolbar().getMenu().clear();
            MenuItem itemRemark = getToolbar().getMenu().add("备注");
            itemRemark.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            itemRemark.setOnMenuItemClickListener(i -> {
                Intent intent = new Intent(UserProfileActivity.this, RemarkActivity.class);
                intent.putExtra("id", mUserIntroduce.getUserProfileId());
                startActivityForResult(intent, Config.Code_NeedRefresh);
                return false;
            });
        }

        setTool();
        if (pageAdapter == null) {
            if (app.isLogin())
                DynamicModel.getInstance().getUserRecord(mUserIntroduce.getUserProfileId())
                        .subscribe(userCensus -> {
                            if (userCensus.getDynamicSize() != 0)
                                titles[0] = "动态(" + userCensus.getDynamicSize() + ")";
                            if (userCensus.getCourseSize() != 0)
                                titles[2] = "课程(" + userCensus.getCourseSize() + ")";
                            pageAdapter.notifyDataSetChanged();
                        });
            pageAdapter = new PageAdapter(getSupportFragmentManager());
            mViewPager.setAdapter(pageAdapter);
            mTabLayout.setupWithViewPager(mViewPager);
        }
        if (mUserIntroduce.getCheckStatus() == 5) {
            identify.setVisibility(View.VISIBLE);
        }
    }

    private class PageAdapter extends FragmentStatePagerAdapter {

        public PageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return UserDynamicFragment.newInstance(mUserIntroduce.getUserProfileId());
                case 1:
                    return IntroduceFragment.newInstance(mUserIntroduce, data);
                case 2:
                    return UserCourseFragment.newInstance(mUserIntroduce.getUserProfileId(), mUserIntroduce.getIntroduce(), data);
                default:
                    return null;
            }
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
//            switch (position) {
//                case 0:
//                    return "动态";
//                case 1:
//                    return "简介";
//                case 2:
//                    return "课程";
//                default:
//                    return null;
//            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        ButterKnife.unbind(this);
    }

    private void setTool() {
        if (mUserIntroduce.getIsAttended() == 0) {
            textAttention.setText("关注");
            imgAttention.setImageResource(R.drawable.attention_other);
        } else {
            imgAttention.setImageResource(R.drawable.ic_attentioned);
            textAttention.setText("已关注");
        }

        llAttention.setOnClickListener(v -> {
            if (!app.isLogin()) {
                startActivity(new Intent(this, PreLoginActivity.class));
                return;
            }
            if (mUserIntroduce.getIsAttended() == 0)
                DynamicModel.getInstance().attention(mUserIntroduce.getUserProfileId(), mUserIntroduce.getUsertype(), XApplication.getInstance().isStudent() ? 2 : 1)
                        .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                        .subscribe(message -> {
                            textAttention.setText("已关注");
                            imgAttention.setImageResource(R.drawable.ic_attentioned);
                            mUserIntroduce.setIsAttended(1);
                            JUtils.Toast("关注成功");
                            setResult(RESULT_OK);
                        });
            else
                DynamicModel.getInstance().unattention(mUserIntroduce.getUserProfileId())
                        .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                        .subscribe(message -> {
                            imgAttention.setImageResource(R.drawable.attention_other);
                            textAttention.setText("关注");
                            mUserIntroduce.setIsAttended(0);
                            JUtils.Toast("取消成功");
                            setResult(RESULT_OK);
                        });
        });

        llTopAttention.setOnClickListener(v -> {
            if (app.isLogin()) {
                Intent intent = new Intent(UserProfileActivity.this, AttentionListActivity.class);
                intent.putExtra("isFans", false);
                intent.putExtra("userId", mUserIntroduce.getUserProfileId());
                startActivity(intent);
            } else
                startActivity(new Intent(this, PreLoginActivity.class));
        });
        llMessage.setOnClickListener(v -> {
            if (app.isLogin())
                RongYunModel.getInstance().chatPerson(this, mUserProfileId + "", mUserIntroduce.getRemarkName() == null ? mUserIntroduce.getUserName() : mUserIntroduce.getRemarkName());
            else
                startActivity(new Intent(this, PreLoginActivity.class));
        });
        llTopFans.setOnClickListener(v -> {
            if (app.isLogin()) {
                Intent intent = new Intent(UserProfileActivity.this, AttentionListActivity.class);
                intent.putExtra("isFans", true);
                intent.putExtra("userId", mUserIntroduce.getUserProfileId());
                startActivity(intent);
            } else
                startActivity(new Intent(this, PreLoginActivity.class));
        });

        if (app.getUserProfileId() == mUserIntroduce.getUserProfileId()) {
            mCover.setOnClickListener(v -> {
                Intent intent = new Intent(UserProfileActivity.this, PhotoChangeActivity.class);
                intent.putExtra("isAvatar", false);
                intent.putExtra("coverPhoto", mUserIntroduce.getCoverPhoto());
                startActivityForResult(intent, 10086);
            });
            mAvatar.setOnClickListener(v -> {
                Intent intent = new Intent(UserProfileActivity.this, PhotoChangeActivity.class);
                intent.putExtra("isAvatar", true);
                intent.putExtra("coverPhoto", ImageModel.getXueDouImage(mUserIntroduce.getHeadUrl()));
                startActivityForResult(intent, 10086);
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            if (fragment != null)
                fragment.onActivityResult(requestCode, resultCode, data);
        }
        if (resultCode == RESULT_OK) {
            loadUserIntroduce();
        }
    }
}